//
//  MulticastViewController.swift
//  testRxSwift
//
//  Created by 火星人 on 2017/7/25.
//  Copyright © 2017年 火星人. All rights reserved.
//

import UIKit
import RxSwift

class MulticastViewController: BaseViewController {
    
    var disposable1: Disposable!
    var disposable2: Disposable!
    var disposable3: Disposable!
    var disposable4: Disposable!

    override func viewDidLoad() {
        super.viewDidLoad()

        let subject = PublishSubject<Int>()
        disposable4 = subject.subscribe { (eve) in
            print("subject \(eve)")
        }
        
        let interval = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
            .multicast(subject)
        
        disposable3 = interval.connect() //connect后，序列开始发射
        
        disposable1 = interval
            .subscribe(onNext: { print("Subscription: 1, Event: \($0)") })
        
        
        delay(4) {
            [weak self] in
            self?.disposable2 = interval
                .subscribe(onNext: { print("Subscription: 2, Event: \($0)") })
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        let dbag = DisposeBag()
        
        disposable1.disposed(by: dbag)
        disposable3.disposed(by: dbag)
        disposable4.disposed(by: dbag)
        if let disposable2 = disposable2 {
            disposable2.disposed(by: dbag)
        }
        
    }


}
